<template>
  <div class="batch-operations">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>批量操作</span>
          <div class="header-controls">
            <el-button type="primary" @click="refreshDevices">
              刷新设备列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 设备选择 -->
      <div class="device-selection">
        <el-card class="selection-card">
          <template #header>
            <div class="selection-header">
              <span>设备选择</span>
              <div class="selection-controls">
                <el-button size="small" @click="selectAll">
                  全选
                </el-button>
                <el-button size="small" @click="selectNone">
                  取消全选
                </el-button>
                <el-button size="small" @click="selectByStatus('online')">
                  选择在线设备
                </el-button>
                <el-button size="small" @click="selectByStatus('offline')">
                  选择离线设备
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 筛选条件 -->
          <div class="filter-section">
            <el-form :model="filterForm" inline>
              <el-form-item label="设备名称">
                <el-input 
                  v-model="filterForm.name" 
                  placeholder="输入设备名称" 
                  @input="filterDevices"
                />
              </el-form-item>
              <el-form-item label="制造商">
                <el-select v-model="filterForm.manufacturer" placeholder="选择制造商" @change="filterDevices">
                  <el-option label="全部" value="" />
                  <el-option 
                    v-for="manufacturer in manufacturers" 
                    :key="manufacturer"
                    :label="manufacturer"
                    :value="manufacturer"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="filterForm.status" placeholder="选择状态" @change="filterDevices">
                  <el-option label="全部" value="" />
                  <el-option label="在线" value="online" />
                  <el-option label="离线" value="offline" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 设备列表 -->
          <div class="device-list">
            <el-table 
              :data="filteredDevices" 
              @selection-change="handleDeviceSelection"
              max-height="400"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="设备名称" min-width="150" />
              <el-table-column prop="ip" label="IP地址" width="120" />
              <el-table-column prop="manufacturer" label="制造商" width="100" />
              <el-table-column prop="model" label="型号" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
                    {{ row.status === 'online' ? '在线' : '离线' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="lastSeen" label="最后在线" width="150">
                <template #default="{ row }">
                  {{ formatDateTime(row.lastSeen) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="selection-summary" v-if="selectedDevices.length > 0">
            <el-alert
              :title="`已选择 ${selectedDevices.length} 个设备`"
              type="info"
              show-icon
              :closable="false"
            />
          </div>
        </el-card>
      </div>
      
      <!-- 批量操作选项 -->
      <div class="batch-operations-section">
        <el-row :gutter="20">
          <!-- 设备管理操作 -->
          <el-col :span="8">
            <el-card class="operation-card">
              <template #header>
                <span>设备管理操作</span>
              </template>
              <div class="operation-buttons">
                <el-button 
                  type="success" 
                  :disabled="selectedDevices.length === 0"
                  @click="batchEnable"
                >
                  批量启用
                </el-button>
                <el-button 
                  type="warning" 
                  :disabled="selectedDevices.length === 0"
                  @click="batchDisable"
                >
                  批量禁用
                </el-button>
                <el-button 
                  type="primary" 
                  :disabled="selectedDevices.length === 0"
                  @click="batchRefresh"
                >
                  批量刷新
                </el-button>
                <el-button 
                  type="danger" 
                  :disabled="selectedDevices.length === 0"
                  @click="batchDelete"
                >
                  批量删除
                </el-button>
              </div>
            </el-card>
          </el-col>
          
          <!-- 配置操作 -->
          <el-col :span="8">
            <el-card class="operation-card">
              <template #header>
                <span>配置操作</span>
              </template>
              <div class="operation-buttons">
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="batchTimeSync"
                >
                  批量时间同步
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="batchReboot"
                >
                  批量重启
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="showBatchConfigDialog"
                >
                  批量配置
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="batchExportConfig"
                >
                  批量导出配置
                </el-button>
              </div>
            </el-card>
          </el-col>
          
          <!-- 监控操作 -->
          <el-col :span="8">
            <el-card class="operation-card">
              <template #header>
                <span>监控操作</span>
              </template>
              <div class="operation-buttons">
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="handleBatchStartRecording"
                >
                  批量开始录像
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="handleBatchStopRecording"
                >
                  批量停止录像
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="handleBatchSubscribeEvents"
                >
                  批量订阅事件
                </el-button>
                <el-button 
                  :disabled="selectedDevices.length === 0"
                  @click="handleBatchUnsubscribeEvents"
                >
                  批量取消订阅
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 操作进度 -->
      <div class="operation-progress" v-if="operationInProgress">
        <el-card class="progress-card">
          <template #header>
            <span>操作进度</span>
          </template>
          <div class="progress-content">
            <div class="progress-info">
              <span>{{ currentOperation }}</span>
              <span>{{ progressText }}</span>
            </div>
            <el-progress 
              :percentage="progressPercentage" 
              :status="progressStatus"
            />
            <div class="progress-details">
              <el-table :data="operationResults" max-height="200">
                <el-table-column prop="deviceName" label="设备" width="150" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                      {{ getStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="message" label="结果" />
              </el-table>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 批量配置对话框 -->
    <el-dialog v-model="batchConfigDialogVisible" title="批量配置" width="60%">
      <el-tabs v-model="activeConfigTab">
        <el-tab-pane label="网络配置" name="network">
          <el-form :model="batchNetworkConfig" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="DHCP">
                  <el-switch v-model="batchNetworkConfig.dhcpEnabled" />
                </el-form-item>
                <el-form-item label="首选DNS">
                  <el-input v-model="batchNetworkConfig.primaryDns" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备用DNS">
                  <el-input v-model="batchNetworkConfig.secondaryDns" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="时间配置" name="time">
          <el-form :model="batchTimeConfig" label-width="120px">
            <el-form-item label="时区">
              <el-select v-model="batchTimeConfig.timezone" placeholder="选择时区">
                <el-option 
                  v-for="tz in timezones" 
                  :key="tz.value"
                  :label="tz.label"
                  :value="tz.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="NTP服务器">
              <el-input v-model="batchTimeConfig.ntpServer" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="录像配置" name="recording">
          <el-form :model="batchRecordingConfig" label-width="120px">
            <el-form-item label="录像质量">
              <el-select v-model="batchRecordingConfig.quality">
                <el-option label="高清" value="high" />
                <el-option label="标清" value="medium" />
                <el-option label="低清" value="low" />
              </el-select>
            </el-form-item>
            <el-form-item label="录像时长(分钟)">
              <el-input-number v-model="batchRecordingConfig.duration" :min="1" :max="1440" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="batchConfigDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applyBatchConfig">应用配置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDevices,
  batchUpdateDevices,
  batchDeleteDevices,
  batchSyncTime,
  batchRebootDevices,
  batchExportConfigs
} from '@/api/device'
import {
  batchStartRecording,
  batchStopRecording
} from '@/api/recording'
import {
  batchSubscribeEvents,
  batchUnsubscribeEvents
} from '@/api/event'

const devices = ref([])
const selectedDevices = ref([])
const filteredDevices = ref([])
const manufacturers = ref([])
const operationInProgress = ref(false)
const currentOperation = ref('')
const operationResults = ref([])
const batchConfigDialogVisible = ref(false)
const activeConfigTab = ref('network')

const filterForm = reactive({
  name: '',
  manufacturer: '',
  status: ''
})

const batchNetworkConfig = reactive({
  dhcpEnabled: false,
  primaryDns: '',
  secondaryDns: ''
})

const batchTimeConfig = reactive({
  timezone: '',
  ntpServer: ''
})

const batchRecordingConfig = reactive({
  quality: 'medium',
  duration: 60
})

const timezones = ref([
  { label: 'UTC+8 (北京时间)', value: 'Asia/Shanghai' },
  { label: 'UTC+0 (格林威治时间)', value: 'UTC' },
  { label: 'UTC-5 (美国东部时间)', value: 'America/New_York' },
  { label: 'UTC-8 (美国太平洋时间)', value: 'America/Los_Angeles' },
  { label: 'UTC+1 (中欧时间)', value: 'Europe/Berlin' },
  { label: 'UTC+9 (日本时间)', value: 'Asia/Tokyo' }
])

// 计算属性
const progressPercentage = computed(() => {
  if (operationResults.value.length === 0 || selectedDevices.value.length === 0) return 0
  return Math.round((operationResults.value.length / selectedDevices.value.length) * 100)
})

const progressText = computed(() => {
  return `${operationResults.value.length} / ${selectedDevices.value.length}`
})

const progressStatus = computed(() => {
  if (progressPercentage.value === 100) {
    const hasError = operationResults.value.some(r => r.status === 'error')
    return hasError ? 'exception' : 'success'
  }
  return 'active'
})

// 加载设备列表
const loadDevices = async () => {
  try {
    const response = await getDevices()
    devices.value = response.data.content || []
    filteredDevices.value = devices.value
    
    // 提取制造商列表
    const manufacturerSet = new Set(devices.value.map(d => d.manufacturer).filter(Boolean))
    manufacturers.value = Array.from(manufacturerSet)
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

// 刷新设备列表
const refreshDevices = () => {
  loadDevices()
}

// 筛选设备
const filterDevices = () => {
  filteredDevices.value = devices.value.filter(device => {
    const nameMatch = !filterForm.name || device.name.toLowerCase().includes(filterForm.name.toLowerCase())
    const manufacturerMatch = !filterForm.manufacturer || device.manufacturer === filterForm.manufacturer
    const statusMatch = !filterForm.status || device.status === filterForm.status
    
    return nameMatch && manufacturerMatch && statusMatch
  })
}

// 设备选择处理
const handleDeviceSelection = (selection) => {
  selectedDevices.value = selection
}

// 全选
const selectAll = () => {
  // 触发表格全选
  const table = document.querySelector('.device-list .el-table')
  if (table) {
    const checkboxes = table.querySelectorAll('.el-checkbox__input')
    checkboxes[0]?.click() // 点击表头复选框
  }
}

// 取消全选
const selectNone = () => {
  selectedDevices.value = []
}

// 按状态选择
const selectByStatus = (status) => {
  selectedDevices.value = filteredDevices.value.filter(device => device.status === status)
}

// 执行批量操作
const executeBatchOperation = async (operation, operationName, apiCall) => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择设备')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要对选中的 ${selectedDevices.value.length} 个设备执行${operationName}操作吗？`,
      `确认${operationName}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    operationInProgress.value = true
    currentOperation.value = operationName
    operationResults.value = []
    
    const deviceIds = selectedDevices.value.map(d => d.id)
    
    // 逐个执行操作以显示进度
    for (const device of selectedDevices.value) {
      try {
        await apiCall([device.id])
        operationResults.value.push({
          deviceName: device.name,
          status: 'success',
          message: '操作成功'
        })
      } catch (error) {
        operationResults.value.push({
          deviceName: device.name,
          status: 'error',
          message: error.message || '操作失败'
        })
      }
    }
    
    const successCount = operationResults.value.filter(r => r.status === 'success').length
    const errorCount = operationResults.value.filter(r => r.status === 'error').length
    
    if (errorCount === 0) {
      ElMessage.success(`${operationName}完成，成功处理 ${successCount} 个设备`)
    } else {
      ElMessage.warning(`${operationName}完成，成功 ${successCount} 个，失败 ${errorCount} 个`)
    }
    
    // 刷新设备列表
    await loadDevices()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${operationName}失败`)
    }
  } finally {
    setTimeout(() => {
      operationInProgress.value = false
    }, 2000)
  }
}

// 批量启用
const batchEnable = () => {
  executeBatchOperation(
    'enable',
    '批量启用',
    (deviceIds) => batchUpdateDevices({ deviceIds, enabled: true })
  )
}

// 批量禁用
const batchDisable = () => {
  executeBatchOperation(
    'disable',
    '批量禁用',
    (deviceIds) => batchUpdateDevices({ deviceIds, enabled: false })
  )
}

// 批量刷新
const batchRefresh = () => {
  executeBatchOperation(
    'refresh',
    '批量刷新',
    (deviceIds) => batchUpdateDevices({ deviceIds, action: 'refresh' })
  )
}

// 批量删除
const batchDelete = () => {
  executeBatchOperation(
    'delete',
    '批量删除',
    (deviceIds) => batchDeleteDevices(deviceIds)
  )
}

// 批量时间同步
const batchTimeSync = () => {
  executeBatchOperation(
    'timeSync',
    '批量时间同步',
    (deviceIds) => batchSyncTime(deviceIds)
  )
}

// 批量重启
const batchReboot = () => {
  executeBatchOperation(
    'reboot',
    '批量重启',
    (deviceIds) => batchRebootDevices(deviceIds)
  )
}

// 显示批量配置对话框
const showBatchConfigDialog = () => {
  batchConfigDialogVisible.value = true
}

// 应用批量配置
const applyBatchConfig = async () => {
  try {
    const deviceIds = selectedDevices.value.map(d => d.id)
    let config = {}
    
    switch (activeConfigTab.value) {
      case 'network':
        config = { ...batchNetworkConfig }
        break
      case 'time':
        config = { ...batchTimeConfig }
        break
      case 'recording':
        config = { ...batchRecordingConfig }
        break
    }
    
    await batchUpdateDevices({ deviceIds, config })
    ElMessage.success('批量配置应用成功')
    batchConfigDialogVisible.value = false
    
  } catch (error) {
    ElMessage.error('批量配置应用失败')
  }
}

// 批量导出配置
const batchExportConfig = async () => {
  try {
    const deviceIds = selectedDevices.value.map(d => d.id)
    const response = await batchExportConfigs(deviceIds)
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/zip' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `batch_configs_${new Date().getTime()}.zip`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('批量导出配置成功')
  } catch (error) {
    ElMessage.error('批量导出配置失败')
  }
}

// 批量开始录像
const handleBatchStartRecording = () => {
  executeBatchOperation(
    'startRecording',
    '批量开始录像',
    (deviceIds) => batchStartRecording(deviceIds)
  )
}

// 批量停止录像
const handleBatchStopRecording = () => {
  executeBatchOperation(
    'stopRecording',
    '批量停止录像',
    (deviceIds) => batchStopRecording(deviceIds)
  )
}

// 批量订阅事件
const handleBatchSubscribeEvents = () => {
  executeBatchOperation(
    'subscribeEvents',
    '批量订阅事件',
    (deviceIds) => batchSubscribeEvents(deviceIds)
  )
}

// 批量取消订阅事件
const handleBatchUnsubscribeEvents = () => {
  executeBatchOperation(
    'unsubscribeEvents',
    '批量取消订阅事件',
    (deviceIds) => batchUnsubscribeEvents(deviceIds)
  )
}

// 格式化函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

const getStatusType = (status) => {
  const types = {
    success: 'success',
    error: 'danger',
    pending: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    success: '成功',
    error: '失败',
    pending: '处理中'
  }
  return texts[status] || status
}

onMounted(() => {
  loadDevices()
})
</script>

<style scoped>
.batch-operations {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.device-selection {
  margin-bottom: 20px;
}

.selection-card {
  background: #f8f9fa;
}

.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selection-controls {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.device-list {
  margin-bottom: 15px;
}

.selection-summary {
  margin-top: 10px;
}

.batch-operations-section {
  margin-bottom: 20px;
}

.operation-card {
  height: 200px;
}

.operation-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.operation-buttons .el-button {
  width: 100%;
}

.operation-progress {
  margin-top: 20px;
}

.progress-card {
  background: #f0f9ff;
}

.progress-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.progress-details {
  margin-top: 10px;
}
</style>